import { message, Upload } from "antd";
import ImgCrop from "antd-img-crop";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import React from "react";
import { AUTH_TOKEN } from "../../constant";
import useUserInfo from "../../hooks/useUserInfo";
import { RcFile } from "antd/es/upload";

const UploadV2 = (props: {
  maxCount: number;
  imgCropAspect: number;
  label: string;
  value: string[];
  onChange: () => any;
}) => {
  const token: string =
    localStorage.getItem(AUTH_TOKEN) || sessionStorage.getItem(AUTH_TOKEN);
  const { data } = useUserInfo();
  const onChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    const files = newFileList.map((f) => ({
      ...f,
      url: f.url || `${import.meta.env.VITE_BASE_URL}/static/` + f.name
    }));
    props.onChange(files);
  };

  // 预览图片
  const onPreview = (file: UploadFile) => {
    async function showFile(file: UploadFile) {
      let src = file.url as string;
      if (!src) {
        src = await new Promise((resolve) => {
          const reader = new FileReader();
          reader.readAsDataURL(file.originFileObj as Blob);
          reader.onload = () => resolve(reader.result as string);
        });
      }
      const image = new Image();
      image.src = src;
      const imgWindow = window.open(src);
      imgWindow?.document.write(image.outerHTML);
    }

    void showFile(file);
  };
  const beforeUpload = (file: RcFile) => {
    const isIMG =
      file.type === "image/png" ||
      file.type === "image/jpeg" ||
      file.type === "image/jpg";
    if (!isIMG) {
      void message.error("请上传正确的文件格式（png,jpeg,jpg,jiff）!");
      return false;
    }
    return true;
  };
  return (
    <ImgCrop
      rotationSlider
      aspect={props.imgCropAspect}
      beforeCrop={(file) => {
        return beforeUpload(file);
      }}
    >
      <Upload
        accept="image/png,image/jpeg,image/jpg"
        method="post"
        progress
        beforeUpload={beforeUpload}
        maxCount={props.maxCount}
        headers={{
          Authorization: "Bearer " + token
        }}
        action={
          `${import.meta.env.VITE_BASE_URL}/upload/` +
          (data?.id as string) +
          "/false"
        }
        listType="picture-card"
        fileList={props.value ?? []}
        onChange={onChange}
        onPreview={onPreview}
        name="file"
      >
        {`+ ${props.label}`}
      </Upload>
    </ImgCrop>
  );
};

export default UploadV2;
